package com.i2works.smartluolong.utils.config;

import com.alibaba.fastjson.JSONObject;
import com.google.common.collect.Maps;
import com.i2works.smartluolong.utils.common.BaseUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.List;
import java.util.Map;

/**
 * @author Liu Yutao <koal@vip.qq.com>
 * @date 2018/6/12 15:50
 */

public class ShiroConfigurationUtils {

    //日志
    private static final Logger logger = LoggerFactory.getLogger(ShiroConfigurationUtils.class);
    //默认filterchain配置文件
    private static final String CONFIG_SHIRO_FILTER_CHAIN_JSON = "config/shiro-filter-chain.json";


    /**
     * 获取filterchain
     */
    public Map<String, String> getShiroFilterChain(String shiroFilterchainUrl) {
        Map<String, String> roleMap = null;
        try {
            roleMap = Maps.newLinkedHashMap();
            File file;
            if (StringUtils.isNotBlank(shiroFilterchainUrl)) {
                file = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX + shiroFilterchainUrl);
            } else {
                file = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX + CONFIG_SHIRO_FILTER_CHAIN_JSON);
            }
            String json = BaseUtils.txt2String(file);
            JSONObject result = JSONObject.parseObject(json);
            List roleList = result.getObject("roles", List.class);
            for (Object role : roleList) {
                JSONObject filter = JSONObject.parseObject(role.toString());
                roleMap.put(filter.getString("url"), filter.getString("role"));
            }
        } catch (FileNotFoundException e) {
            roleMap.put("/**", "anon");
            logger.error("未找到shiro的拦截器链的配置文件....");
            logger.error("将添加全放行规则（/**[anon]）到拦截器链中....");
        }
        return roleMap;
    }
}
